//“给你一个m×n的二维数组，请你按照顺时针螺旋顺序，返回数组中的所有元素。”

function spiralOrder(matrix) {
    let list = [];
    //当二维数组是空或任何一个维度是0，直接返回
    if (matrix == null || matrix.length == 0 || matrix[0].length == 0) {
        return list;
    }
    //m是矩阵的行数
    let m = matrix.length;
    //n是矩阵的列数
    let n = matrix[0].length;
    //二维数组的层数，取决于行和列的较小值
    let size = (Math.min(m, n)+1)/2;
    //大循环，从外向内逐层遍历矩阵
    for(let i=0; i<size; i++) {
        //从左到右遍历“上边”
        for (let j=i; j<n-i; j++) {
            list.push(matrix[i][j]);
        }
        //从上到下遍历“右边”
        for (let j=i+1; j<m-i; j++) {
            list.push(matrix[j][(n-1)-i]);
        }
        //从右到左遍历“下边”
        for (let j=i+1; j<n-i && (m-1)-i>i; j++) {
            list.push(matrix[(m-1)-i][(n-1)-j]);
        }
        //从下到上遍历“左边”
        for (let j=i+1; j<m-1-i && i<(n-1)-i; j++) {
            list.push(matrix[(m-1)-j][i]);
        }
    }
    return list;
}

    




let matrix = [
        [ 1,  2,  3,  4,  5  ],
        [ 6,  7,  8,  9,  10 ],
        [ 11, 12, 13, 14, 15 ],
        [ 16, 17, 18, 19, 20 ]
];
let matrix2 = [
        [1,  2,  3 ],
        [4,  5,  6 ],
        [7,  8,  9 ],
        [10, 11, 12 ],
        [13, 14, 15 ]
];
let resultList1 = spiralOrder(matrix);
console.log(resultList1);
let resultList2 = spiralOrder(matrix2);
console.log(resultList2);
